
import React, { memo, useEffect, useRef, useState } from 'react';
import { ScrollViewWrapper } from './style';
import IconArrowLeft from 'src/assets/svg/icon-arrow-left';
import IconArrowRight from 'src/assets/svg/icon-arrow-right';

const ScrollView = memo((props) => {
  // 1. 定义内容的状态
  const [showRight, setShowRight] = useState(false);
  const [showLeft, setShowLeft] = useState(false);
  //   const [posIndex, setPosIndex] = useState(0);

  // 不需要组件重新刷新
  // const [totalDistance, setTotalDistance] = useState(0);

  const posIndex = useRef(0);
  const totalDistance = useRef();
  // 2. 组件渲染完毕，判断是否显示右侧按钮
  const scrollContentRef = useRef();
  useEffect(() => {
    const scrollWidth = scrollContentRef.current.scrollWidth;
    const clientWidth = scrollContentRef.current.clientWidth;

    const distance = scrollWidth - clientWidth;
    totalDistance.current = distance;

    setShowRight(totalDistance.current > 0);
  }, [props.children]);

  /** 3. 事件处理 */
  function controlClickHandle(isRight) {
    const newIndex = isRight ? posIndex.current + 1 : posIndex.current - 1;
    const newEl = scrollContentRef.current.children[newIndex];

    const newOffsetLeft = newEl.offsetLeft;
    scrollContentRef.current.style.transform = `translate(-${newOffsetLeft}px)`;

    posIndex.current = newIndex;
    //   是否继续显示右侧的按钮
    setShowRight(totalDistance.current > newOffsetLeft);
    setShowLeft(newOffsetLeft > 0);
  }
  return (
    <ScrollViewWrapper>
      {showLeft && (
        <div className="left" onClick={(e) => controlClickHandle(false)}>
          <IconArrowLeft />
        </div>
      )}

      {showRight && (
        <div className="right" onClick={(e) => controlClickHandle(true)}>
          <IconArrowRight />
        </div>
      )}

      <div className="scroll-content">
        <div className="scroll" ref={scrollContentRef}>
          {props.children}
        </div>
      </div>
    </ScrollViewWrapper>
  );
});



export default ScrollView;
